/**
 * @projectName interview_-assistant
 * @package org.example.controller
 * @className org.example.controller.PdfController
 * @copyright Copyright 2025 Thunisoft, Inc All rights reserved.
 */
package org.example.controller;

import org.example.domain.vo.FileConversionRequest;
import org.example.result.Result;
import org.example.service.FileConversionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * PdfController
 * @description
 * @author admin
 * @date 2025/4/15 11:03
 * @version TODO
 */
@RestController
@RequestMapping("/api/file")
public class PdfController {

    @Autowired
    private FileConversionService fileConversionService;

    /**
     * 将PDF文件转换为TXT文件
     */
    @PostMapping("/convert/pdf-to-txt")
    public Result<String> convertPdfToTxt(@RequestBody FileConversionRequest request) {
        try {
            // 处理路径中的反斜杠
            String pdfPath = request.getPdfPath().replace("\\", "/");
            String txtPath = request.getTxtPath().replace("\\", "/");

            return fileConversionService.convertPdfToTxt(pdfPath, txtPath);
        } catch (Exception e) {
            return Result.error("转换失败: " + e.getMessage());
        }
    }

    /**
     * 上传PDF文件并指定保存路径
     */
    @PostMapping("/upload-and-convert")
    public Result<String> uploadAndConvertPdf(
            @RequestParam("file") MultipartFile file,
            @RequestParam("outputPath") String outputPath) {
        try {
            if (file.isEmpty()) {
                return Result.error("请选择要上传的PDF文件");
            }

            if (!file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
                return Result.error("只支持PDF文件格式");
            }

            // 解码输出路径
            String decodedOutputPath = URLDecoder.decode(outputPath, StandardCharsets.UTF_8.name());

            // 创建临时文件
            File tempPdfFile = File.createTempFile("temp_", ".pdf");
            file.transferTo(tempPdfFile);

            // 转换并保存
            Result<String> result = fileConversionService.convertPdfToTxt(
                    tempPdfFile.getAbsolutePath(),
                    decodedOutputPath
            );

            // 删除临时文件
            tempPdfFile.delete();

            return result;
        } catch (Exception e) {
            return Result.error("文件处理失败: " + e.getMessage());
        }
    }
}